package com.walnut.servlet;

import com.walnut.dao.FoodDao;
import com.walnut.dao.OrderDao;
import com.walnut.dao.impl.FoodDaoImpl;
import com.walnut.dao.impl.OrderDaoImpl;
import com.walnut.pojo.Food;
import com.walnut.pojo.Order;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.time.LocalDate;

@WebServlet("/addOrder")
public class AddOrderServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        log("正在存入订单信息");
        ServletContext context = getServletContext();
        FoodDao foodDao = new FoodDaoImpl();
        OrderDao orderDao = new OrderDaoImpl();
        Integer goodsTypeId = Integer.parseInt(request.getParameter("goodsTypeId")); // 确保参数名一致
        try {

            Food food = foodDao.selectById(goodsTypeId);
            if (food == null) {
                context.setAttribute("message", "找不到该食品");
                request.getRequestDispatcher("/foodList").forward(request, response);
                return;
            }

            String purchaser = (String) context.getAttribute("loginer");
            if (purchaser == null || purchaser.isEmpty()) {
                context.setAttribute("message", "未指定购买者");
                request.getRequestDispatcher("/foodList").forward(request, response);
                return;
            }

            Order order = Order.builder()
                    .goodsName(food.getFoodName())
                    .goodsTypeId(food.getFoodId())
                    .goodsType("食品")
                    .price(food.getPrice())
                    .purchaser(purchaser)
                    .createTime(Date.valueOf(LocalDate.now()))
                    .updateTime(Date.valueOf(LocalDate.now()))
                    .build();
            int count = orderDao.insert(order);
            if (count == 1) {
                context.setAttribute("message", "购买成功");
            } else {
                context.setAttribute("message", "购买失败, 服务器内部错误");
            }
        } catch (NumberFormatException e) {
            context.setAttribute("message", "食品ID无效");
        } catch (SQLException e) {
            context.setAttribute("message", "数据库操作失败");
        } catch (Exception e) {
            context.setAttribute("message", "服务器内部错误");
        }
    }
}